<template>
  <section :key="uniqueProject" class="diseasesHealth">
    <div class="operate">
      <ElButton type="primary" round plain @click="upMassagetPrice"
        >保存修改</ElButton
      >
      <ElUpload
        class="up-excel-button"
        :action="url.excel"
        :headers="headers"
        :show-file-list="false"
        name="excel"
        :on-success="upExcelSuccess"
        :on-error="upExcelError"
      >
        <ElButton type="primary" round plain>批量导入</ElButton>
      </ElUpload>
      <ElButton type="primary" round plain @click="exportExcel"
        >导出表格</ElButton
      >
      <ElButton type="primary" round plain @click="getTemplate"
        >下载模板</ElButton
      >
    </div>
    <MemberSelector
      class="members"
      :no-members.sync="noMembers"
      @selected="filter"
    />
    <ElTable
      :class="{noMembers: noMembers}"
      :data="showProductList"
      :stripe="true"
      :highlight-current-row="true"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <ElTableColumn align="center" type="selection" width="60">
      </ElTableColumn>
      <ElTableColumn
        align="center"
        prop="commodity_name"
        width="130"
        label="产品名称"
      >
      </ElTableColumn>
      <ElTableColumn
        align="center"
        prop="product_type"
        min-width="180"
        label="产品类别"
      >
      </ElTableColumn>
      <ElTableColumn
        align="center"
        prop="fine_type"
        min-width="180"
        label="精细分类"
      >
      </ElTableColumn>
      <ElTableColumn align="center" prop="price" min-width="180" label="价格">
        <template slot-scope="scope">
          <ElInput
            v-model="scope.row.price"
            placeholder="0"
            class="input"
            @change="changeEditStatus"
            >{{ scope.row.price }}</ElInput
          >元/{{ scope.row.company || '次' }}
        </template>
      </ElTableColumn>
      <ElTableColumn align="center" prop="methods" min-width="180" label="操作">
        <template slot-scope="scope">
          <ElButton
            size="medium"
            plain
            round
            type="primary"
            @click="handleDelete(scope.row)"
            >删除</ElButton
          >
          <ElButton
            size="medium"
            plain
            type="primary"
            round
            @click="handleEdit(scope.row.id)"
            >编辑</ElButton
          >
        </template>
      </ElTableColumn>
    </ElTable>
    <ElPagination
      v-if="productList.length > 20"
      :current-page.sync="currentPage"
      :page-size="pageSize"
      :page-sizes="pageSizes"
      layout="sizes, prev, pager, next"
      :total="productList.length"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    >
    </ElPagination>
  </section>
</template>

<script>
import _ from 'lodash';
import Cookie from 'js-cookie';
import {http, catchAppError} from '@/util';
import {pageSizes, menusNavigation} from '@/store';
import url from '@/config';
import MemberSelector from './MemberSelector.vue';
import toast from '@/toast';
import changeEditStatus from './ProjectEditStatus';

export default {
  name: 'ProductList',
  components: {MemberSelector},
  props: {
    refresh: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      url,
      uniqueProject: 0,
      pageSize: 20,
      currentPage: 1,
      pageSizes,
      params: {
        shop_type: 6,
        grade_id: null
      },
      noMembers: true,
      headers: {
        token: Cookie.get('token')
      },
      productList: [],
      showProductList: [],
      multipleSelection: []
    };
  },
  watch: {
    refresh() {
      if (this.refresh) {
        this.getProductList();
      }
    }
  },
  updated() {
    changeEditStatus(false);
  },
  beforeMount() {
    this.getProductList();
  },
  methods: {
    changeEditStatus,
    handleSelectionChange(val) {
      this.multipleSelection[this.currentPage - 1] = val;
    },
    getTemplate() {
      http
        .post(url.getTemplate, {type: 1})
        .then(res => {
          window.location.href = `//${res.url}`;
        })
        .catch(catchAppError);
    },
    exportExcel() {
      const q = _.reduce(this.multipleSelection, (a, b) => _.concat(a, b), []);
      const idList = q.map(({id}) => id);
      const params = {
        isAll: 2,
        type: 3,
        idList: []
      };
      if (idList.length === this.productList.length) {
        params.isAll = 1;
      } else {
        params.idList = idList;
      }
      if (!params.idList.length && params.isAll === 2) {
        toast('导出表格勾选内容不能为空！');
        return;
      }
      http
        .post(url.exportExcel, params)
        .then(res => {
          window.location.href = `//${res.url}`;
        })
        .catch(catchAppError);
    },
    handleCurrentChange(val) {
      this.showProductList = _.chunk(this.productList, this.pageSize)[val - 1];
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.handleCurrentChange(1);
      this.multipleSelection = [];
    },
    getProductList() {
      http
        .post(url.productList, this.params)
        .then(res => {
          this.productList = res;
          this.handleCurrentChange(1);
        })
        .catch(catchAppError);
    },
    filter(id) {
      this.params.grade_id = id;
      this.getProductList();
    },
    handleDelete({id}) {
      http
        .post(url.deleteProduct, {commodity_id: id})
        .then(() => {
          this.$message({
            message: '删除成功',
            duration: 5000,
            type: 'success'
          });
          this.getProductList();
        })
        .catch(catchAppError);
    },
    handleEdit(id) {
      menusNavigation.navTab('ProjectNew', '0', {id, nav: '0'});
    },
    upExcelSuccess(res) {
      if (res.code === 1) {
        this.$message({
          message: '文件导入成功',
          duration: 5000,
          type: 'success'
        });
        this.uniqueProject = _.uniqueId();
      } else {
        this.$message({
          message: res.msg,
          duration: 5000,
          type: 'error'
        });
      }
    },
    upExcelError() {
      this.$message({
        message: '文件导入失败',
        duration: 5000,
        type: 'error'
      });
    },
    upMassagetPrice() {
      const params = {
        data: this.showProductList.map(({price, id}) => ({price, id}))
      };
      http
        .post(url.upProductPrice, params)
        .then(() => {
          toast('信息修改成功！');
          changeEditStatus(false);
        })
        .catch(catchAppError);
    }
  }
};
</script>

<style lang="scss">
.up-excel-button {
  display: inline-block;
  margin-right: 10px;
  margin-left: 10px;
}
</style>
